package com.attendancesystem.controller;

import com.attendancesystem.service.ChangePasswordService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;



import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet(name = "ChangePasswordController", value = "/ChangePasswordController")
public class ChangePasswordController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/ChangePassword.jsp").forward(request,response);
//        response.sendRedirect("./WEB-INF/views/ChangePassword.jsp");



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JsonNode rootNode = objectMapper.readTree(request.getReader());
        String newPassword = rootNode.get("newPassword").asText();
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        ChangePasswordService changePasswordService = new ChangePasswordService();
        if(changePasswordService.changePassword(username,newPassword)){
            response.getWriter().write("{\"status\":\"success\"}");
        }
        else{
            response.getWriter().write("{\"status\":\"failed\"}");
        }




    }
}
